<template>
  <div>
    <el-dialog
      :title="goodsForm.id ? '编辑' : '新增'"
      :visible.sync="is.show"
      :before-close="cancel"
      @opened="createEditor"
    >
      <!-- 表单主体 -->
      <el-form :model="goodsForm" ref="goodsForm" :rules="rules">
        <!-- 一级分类 -->
        <el-form-item
          label="一级分类"
          prop="first_cateid"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="goodsForm.first_cateid"
            placeholder="请选择活动区域"
            @change="changeFirstId"
          >
            <el-option
              :label="item.catename"
              v-for="item in cateList"
              :key="item.id"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 二级分类 -->
        <el-form-item
          label="二级分类"
          prop="second_cateid"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="goodsForm.second_cateid"
            placeholder="请选择活动区域"
          >
            <el-option
              v-for="item in secondArr"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 商品名称 -->
        <el-form-item
          label="商品名称"
          prop="goodsname"
          :label-width="formLabelWidth"
        >
          <el-input v-model="goodsForm.goodsname" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 价格 -->
        <el-form-item label="价格" prop="price" :label-width="formLabelWidth">
          <el-input v-model="goodsForm.price" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 市场价格 -->
        <el-form-item
          label="市场价格"
          prop="market_price"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="goodsForm.market_price"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <!-- 上传图片 -->
        <el-form-item label="图片" prop="img" :label-width="formLabelWidth">
          <el-upload
            action=""
            list-type="picture-card"
            :file-list="arr"
            :auto-upload="false"
            :on-change="changeImg"
            :limit="1"
            :on-exceed="
              () => {
                $message.error('超出上传限制');
              }
            "
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <!-- 商品规格 -->
        <el-form-item
          label="商品规格"
          prop="specsid"
          :label-width="formLabelWidth"
        >
          <el-select
            @change="changeAttrs"
            v-model="goodsForm.specsid"
            placeholder="请选择活动区域"
          >
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 规格属性 -->
        <el-form-item
          label="规格属性"
          prop="specsattr"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="goodsForm.specsattr"
            multiple
            placeholder="请选择活动区域"
          >
            <el-option
              v-for="item in attrsArr"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item
          label="商品描述"
          prop="status"
          :label-width="formLabelWidth"
        >
          <div id="editor"></div>
        </el-form-item>

        <!-- 是否新品 -->
        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-switch
            v-model="goodsForm.isnew"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>

        <!-- 是否热卖 -->
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-switch
            v-model="goodsForm.ishot"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>

        <!-- 状态 -->
        <el-form-item label="状态" prop="status" :label-width="formLabelWidth">
          <el-switch
            v-model="goodsForm.status"
            active-color="#13ce66"
            inactive-color="#ccc"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="enter">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
//引入富文本编辑器
import E from "wangeditor";
//引入辅助性函数
import { mapState, mapActions } from "vuex";
//调用添加或修改接口  获取一条数据接口
import { addOreditGoods, goodsInfo } from "../../request/api";
export default {
  data() {
    //自定义验证规则
    const uploadImg = (a, b, callback) => {
      if (this.goodsForm.img == "") {
        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      goodsForm: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      },
      arr: [], //回显图片的数组
      editor: null, //编辑器的初始值
      secondArr: [], //二级分类的数组
      attrsArr: [], //规格属性的数组
      formLabelWidth: "120px",
      //自定义规则验证
      rules: {
        first_cateid: {
          required: true,
          message: "请选择一级分类",
          trigger: "blur",
        },
        second_cateid: {
          required: true,
          message: "请选择二级分类",
          trigger: "blur",
        },
        goodsname: {
          required: true,
          message: "请输入商品名称",
          trigger: "blur",
        },
        price: { required: true, message: "请输入商品价格", trigger: "blur" },
        market_price: {
          required: true,
          message: "请输入市场价格",
          trigger: "blur",
        },
        img: { required: true, validator: uploadImg, trigger: "blur" },
        specsid: { required: true, message: "请选择商品规格", trigger: "blur" },
        specsattr: {
          required: true,
          message: "请选择规格属性",
          trigger: "blur",
        },
      }, //规则验证
    };
  },

  //计算属性 用来使用辅助性函数 mapState
  computed: {
    //这是商品管理的数组
    ...mapState("goods", ["goodsList", "is"]),
    //这是一 二 级分类的数组
    ...mapState("cate", ["cateList"]),
    //商品规格的数组
    ...mapState("specs", ["specsList"]),
  },

  //方法 用来使用辅助性函数 mapActions
  methods: {
    ...mapActions("goods", ["getGoods", "getGoodsTotal"]),
    ...mapActions("cate", ["getCate"]),
    ...mapActions("specs", ["getSpecs"]),

    //创建编辑器
    createEditor() {
      //获取实例
      this.editor = new E("#editor");
      //创建编辑器
      this.editor.create();
      //给编辑器一个初始值  解决回显错误
      this.editor.txt.html(this.goodsForm.description);
    },

    //选择图片事件
    changeImg(file) {
      this.goodsForm.img = file.raw;
    },

    //点击一级分类 出现二级分类数据
    changeFirstId(id) {
      //这是为了每次点击一级分类的时候 清除二级分类的数据
      if (!this.goodsForm.id) {
        this.goodsForm.second_cateid = "";
      }
      //筛选出符合条件的二级分类
      let arr = this.cateList.filter((val) => {
        return id == val.id;
      });
      //赋值
      this.secondArr = arr[0].children;
    },

    //选择商品规格 出现对应的规格属性
    changeAttrs(id) {
      //这是为了每次点击商品规格的时候 清除规格属性的数据
      this.goodsForm.specsattr = "";
      let arr = this.specsList.filter((val) => {
        return id == val.id;
      });
      this.attrsArr = arr[0].attrs;
    },

    //数据回显用的事件
    dataForm(id) {
      goodsInfo({ id }).then((res) => {
        //这是回显图片
        this.arr.push({
          url: res.list.img,
        });
        //回显数据
        this.goodsForm = res.list;
        //回显规格属性
        this.goodsForm.specsattr = res.list.specsattr.split(",");
        //通过这个判断是否是编辑
        this.goodsForm.id = id;
        //通过一级分类id 获取二级分类的数据
        this.changeFirstId(this.goodsForm.first_cateid);

        setTimeout(() => {
          //回显富文本编辑器的内容
          this.goodsForm.description = this.editor.txt.html(
            this.goodsForm.description
          );
        }, 300);
      });
    },

    //点击取消事件
    cancel() {
      // this.rmfwb();
      //关闭弹窗
      this.$store.commit("goods/changeDialog", false);
      //清空表单
      this.goodsForm = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "这是默认值",
        specsid: "",
        specsattr: "",
        isnew: 1,
        ishot: 1,
        status: 1,
      };
      //清除表单验证
      this.$refs.goodsForm.resetFields();
      //清除图片
      this.arr = [];
      //销毁编辑器 节省性能
      this.editor.destroy();
    },

    //点击确认事件
    enter() {
      let url = this.goodsForm.id ? "goodsedit" : "goodsadd";
      //验证是否填入
      this.$refs.goodsForm.validate((val) => {
        if (val) {
          this.goodsForm.specsattr = this.goodsForm.specsattr.join(",");
          //获取编辑器的内容
          this.goodsForm.description = this.editor.txt.html();
          addOreditGoods(url, this.goodsForm).then((res) => {
            if (res.code == 200) {
              //成功提示
              this.$message.success(res.msg);
              //关闭弹窗
              this.cancel();
              //重新获取数据
              this.getGoods();
              //重新获取总条数
              this.getGoodsTotal();
            } else {
              //失败提示
              this.$message.error(res.msg);
              //回显规格属性
              this.goodsForm.specsattr = this.goodsForm.specsattr.split(",");
            }
          });
        }
      });
    },
  },

  //挂载完成
  mounted() {
    if (this.$store.state.cate.cateList.length == 0) {
      this.getCate();
    }
    this.getSpecs(true);
    this.getGoods();
  },
};
</script>


<style scoped>
</style>